<?php
namespace app\api\controller\v1;

use app\api\model\Address as Addr;
use think\Request;
use think\Validate;

class Address extends Base
{

    public function index(Addr $addr,Request $request){

        $addr = $addr->lists($request->header('token'));

        return $this->success($addr);

    }

//

    public function store(Addr $addr,Request $request)
    {

        $validate = new Validate([
            'name' => 'require',
            'mobile' => 'require',
            'province' => 'require',
            'city' => 'require',
            'country' => 'require',
            'detail' => 'require',
        ],[
            'name.require'=>'姓名不能为空',
            'mobile.require'=>'联系电话不能为空',
            'province.require'=>'省不能为空',
            'city.require'=>'城市不能为空',
            'country.require'=>'区/县不能为空',
            'detail.require'=>'详细地址不能为空',
        ]);
        $data = $request->param();

        if (!$validate->check($data)) {

            return $this->error($validate->getError());
        }

        $token = $request->header('token');
        $data = $request->except('version');

        $address = $addr->add($token,$data);

        if ($address){

            return $this->success();

        }

        return $this->error('添加失败');

    }


    public function getDetail(Addr $addr,$id)
    {

        $addr = $addr->getDetail($id);

        if ($addr){

            return $this->success($addr);
        }

        return $this->error();
    }

    public function modify(Request $request)
    {
        $validate = new Validate([
            'name' => 'require',
            'mobile' => 'require',
            'province' => 'require',
            'city' => 'require',
            'country' => 'require',
            'detail' => 'require',
        ],[
            'name.require'=>'姓名不能为空',
            'mobile.require'=>'联系电话不能为空',
            'province.require'=>'省不能为空',
            'city.require'=>'城市不能为空',
            'country.require'=>'区/县不能为空',
            'detail.require'=>'详细地址不能为空',
        ]);
        $data = $request->param();

        if (!$validate->check($data)) {

            return $this->error($validate->getError());
        }

        $data = $request->except('version');

        $address = Addr::update($data);

        if ($address){

            return $this->success();

        }

        return $this->error('更新失败');

    }

    public function del($id)
    {
        $addr = Addr::destroy($id);

        if ($addr){

            return $this->success();
        }

        return $this->error();

    }
}
